var hurl = "http://ws.rovine.cn";
if(document.body){
	var w = document.body.clientWidth;
	var h = document.body.clientHeight;
}
var z = (297 / 210).toFixed(3);

/*
 * 封装的ajax 
 * 使用方法：
 * let data= {
 * 		url:"路径",
 * 		data:{
 * 			参数:值,.......
 * 		}
 * }
 * ajax(data,function(res){
 * 		console.log(res);
 * })
 */
function ajax(data, func) {
	mui.showLoading("正在加载..", "div");
	$.ajax({
		type: "POST",
		url: hurl + data.url,
		dataType: "json",
		data: data.data,
		error: function(err) {
			//console.log("失败:" + err);
			console.log("失败:" + JSON.stringify(err));
			//mui.toast("图片上传失败，请重新上传");
			mui.toast("网络出错，请重试！")
		},
		success: function(data) {
			
			if(data.code == -1) {
				console.log(data);
				if(data.message == "访问令牌不存在或已失效") {
					mui.toast("访问令牌不存在或已失效，请退出从新登陆");
				} else {
					mui.toast(data.message);
				}
			}
			if(data.code == 1) {
				func(data);
			}
		},
		complete: function() {
			mui.hideLoading();
		}
	});
}

function layimg(ceng){
	if(ceng == 1){
	 img =	'images/60x60.gif'
	}else if(ceng == 2){
	 img =	'../images/60x60.gif'
	}
	document.body.removeAttribute('data-imagelazyload');
	mui(document).imageLazyload({  
	    placeholder: img,  
	    autoDestroy: false  
	});
}

function ajaxnohide(data, func) {
	mui.showLoading("正在加载..", "div");
	$.ajax({
		type: "POST",
		url: hurl + data.url,
		dataType: "json",
		data: data.data,
		error: function(err) {
			//console.log("失败:" + err);
			console.log("失败:" + JSON.stringify(err));
			//mui.toast("图片上传失败，请重新上传");
			mui.toast("网络出错，请重试！")
		},
		success: function(data) {
			console.log(data);
			if(data.code == -1) {
				if(data.message == "访问令牌不存在或已失效") {
					mui.toast("访问令牌不存在或已失效，请退出从新登陆");
				} else {
					mui.toast(data.message);
				}
			}
			if(data.code == 1) {
				func(data);
			}
		}
	});
}
/*
 * 判断是移动还是pc
 */
function gomatch() {
                if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) {
                    /*window.location.href="你的手机版地址";*/
                    return "mobile";
                }
                else {
                    /*window.location.href="你的电脑版地址";    */
                    return "pc";
                }
                
            }
/*
 * 判断是什么系统
 */
function getxitong() {
    var u = navigator.userAgent, app = navigator.appVersion;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
    var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    if (isAndroid) {
       //这个是安卓操作系统
       return "android";
    }
    if (isIOS) {
　　　　//这个是ios操作系统
	   return "ios";
    }
}
/*
 * 
 */
function g(id){
	return document.getElementById(id);
}


/*
 * 封装的用于上传base64格式的文件
 * 用法和上面一样
 */
function ajaxbase64(data, func) {
	mui.showLoading("正在加载..", "div");
	$.ajax({
		type: "post",
		url: hurl + data.url,
		dataType: "json",
		data: data.data,
		error: function(err) {
			//console.log("失败:" + err);
			console.log("失败:" + JSON.stringify(err));
			mui.toast("图片上传失败，请重新上传");
		},
		success: function(data) {
			console.log(data);
			if(data.code == -1) {
				if(data.message == "访问令牌不存在或已失效") {
					mui.toast("访问令牌不存在或已失效，请退出从新登陆");
				} else {
					mui.toast(data.message);
				}
			}
			if(data.code == 1) {
				func(data);
			}
		},
		complete: function() {
			mui.hideLoading();
		}
	});
}
/*
 * 获取acctoken的函数，直接可以调用方法获取token
 */
function acctoken() {
	var access_token = null
	try {
		var value = localStorage.getItem('accesstoken') || "c99565f715045122a9ba96fd0759a48d";
		if(value) {
			access_token = value
		}
	} catch(e) {}
	return access_token;

}
/*
 * base64的字符串转成blob
 */

function dataURItoBlob(dataURI) {
	var byteString = atob(dataURI.split(',')[1]);
	var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
	var ab = new ArrayBuffer(byteString.length);
	var ia = new Uint8Array(ab);
	for(var i = 0; i < byteString.length; i++) {
		ia[i] = byteString.charCodeAt(i);
	}
	return new Blob([ab], {
		type: mimeString
	});
}
/*
 * base64的字符串转成blob
 */
function b64toBlob(b64Data, contentType='', sliceSize=512) {
        const byteCharacters = atob(b64Data);
        const byteArrays = [];

        for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            const slice = byteCharacters.slice(offset, offset + sliceSize);

            const byteNumbers = new Array(slice.length);
            for (let i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }

            const byteArray = new Uint8Array(byteNumbers);

            byteArrays.push(byteArray);
        }

      const blob = new Blob(byteArrays, {type: contentType});
      return blob;
}

/*
 *原生js 上传文件 
 */
function upladfile(files, func) {
	let xhr = null,
		url = hurl + '/api/Image/upload',
		form = new FormData();
	form.append("image", files); // 文件对象
	form.append("access_token", acctoken()); // 可以增加表单数据
	xhr = new XMLHttpRequest(); // XMLHttpRequest 对象
	xhr.open("post", url, true); //post方式，url为服务器请求地址，true 该参数规定请求是否异步处理。
	xhr.onload = function(evt) {
		var data = JSON.parse(evt.target.responseText);
		func(data);
	}
	xhr.onerror = function() { //请求失败 
		mui.toast("文件上传失败");
	}; 
	xhr.send(form); //开始上传，发送form数据
}

function upladbase64(base64, func) {
	let xhr = null,
		url = hurl + '/api/Image/upload',
		form = new FormData();
	form.append("base64", base64); // 文件对象
	form.append("access_token", acctoken()); // 可以增加表单数据
	xhr = new XMLHttpRequest(); // XMLHttpRequest 对象
	xhr.open("post", url, true); //post方式，url为服务器请求地址，true 该参数规定请求是否异步处理。
	xhr.onload = function(evt) {
		var data = JSON.parse(evt.target.responseText);
		func(data);
	}
	xhr.onerror = function(err) { //请求失败 
		console.log(err);
		mui.toast("文件上传失败");
	}; 
	xhr.send(form); //开始上传，发送form数据
}

function upladfile2(file1, func) {
	let files = file1 || null,
		xhr,
		url = hurl + '/api/Image/upload',
		form = new FormData();
	form.append("image", files); // 文件对象
	form.append("access_token", acctoken()); // 可以增加表单数据
	xhr = new XMLHttpRequest(); // XMLHttpRequest 对象
	xhr.open("post", url, true); //post方式，url为服务器请求地址，true 该参数规定请求是否异步处理。
	xhr.onload = function(evt) {
		var data = JSON.parse(evt.target.responseText);
		func(data);
	}
	xhr.onerror = function() { //请求失败
		mui.toast("文件上传失败");
	};
	xhr.send(form); //开始上传，发送form数据
}

/*
 * 查看图片是否存在
 */
function ishasimg(pathImg) {
	var ImgObj = new Image();
	ImgObj.src = pathImg;
	//console.log(ImgObj);
	if(ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) {
		return true;
	} else {
		return false;
	}
}

/*
 * 获取路径？后面的参数
 */
function getrequest() {
	var url = location.search; //获取url中"?"符后的字串  
	var theRequest = new Object();
	if(url.indexOf("?") != -1) {
		var str = url.substr(1);
		strs = str.split("&");
		for(var i = 0; i < strs.length; i++) {
			theRequest[strs[i].split("=")[0]] = unescape(decodeURI(strs[i].split("=")[1]));
		}
	}
	return theRequest;
}


 function getUrlParam(name) {
    var url = location.href; //获取url中"?"符后的字串
    if (url.indexOf("?") != -1) {    //判断是否有参数
        var str = url.substr(url.indexOf("?")); //从第一个字符开始 因为第0个是?号 获取所有除问号的所有符串
        var strs = str.split("=");   //用等号进行分隔 （因为知道只有一个参数 所以直接用等号进分隔 如果有多个参数 要用&号分隔 再用等号进行分隔）
        return decodeURI(strs[1])         //直接弹出第一个参数 （如果有多个参数 还要进行循环的）
    }
}


/*
 * 根据路径返回图片的base64
 */
function getBase64Image3(imgurl) {
	let img = new Image();
	img.scr = imgurl;
	let div = document.createElement('div');
	div.appendChild(img);
	img.onload = function() {
		let canvas = document.createElement("canvas");
		canvas.width = img.width;
		canvas.height = img.height;
		let ctx = canvas.getContext("2d");
		ctx.drawImage(img, 0, 0, img.width, img.height);
		let ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
		let dataURL = canvas.toDataURL("image/" + ext);
		console.log(dataURL)
		return {
			dataURL: dataURL,
			type: "image/" + ext
		};

	}
	img.onerror = function(err) {
		console.log("error!")
		console.log(err);
	};

}

function getBase64Image4(imgurl,fun) {
	let img = new Image();
	img.scr = imgurl;
	let div = document.createElement('div');
	div.appendChild(img);
	img.onload = function() {
		let canvas = document.createElement("canvas");
		canvas.width = img.width;
		canvas.height = img.height;
		let ctx = canvas.getContext("2d");
		ctx.drawImage(img, 0, 0, img.width, img.height);
		let ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
		let dataURL = canvas.toDataURL("image/" + ext);
		console.log(dataURL)
		let list = {
			dataURL: dataURL,
			type: "image/" + ext
		}
		fun(list);
		/*return {
			dataURL: dataURL,
			type: "image/" + ext
		};*/
	}
	img.onerror = function(err) {
		console.log("error!")
		console.log(err);
	};

}

/*
 * 压缩图片
 */
function getBase64Image(imgurl, fun) {
	//mui.toast("开始压缩图片");
	mui.showLoading("正在压缩");
	let img = new Image();
	img.src = imgurl;
	let div = document.createElement('div');
	div.appendChild(img);
	img.onload = function() {
		var canvas = document.createElement("canvas");
		let imgw = img.width / 1.5;
		let imgh = img.height / 1.5;
		canvas.width = imgw;
		canvas.height = imgh;
		var ctx = canvas.getContext("2d");
		ctx.drawImage(img, 0, 0, imgw, imgh);
		var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
		var dataURL = canvas.toDataURL("image/" + ext);
		console.log(dataURL);
		if(dataURL.length > 2097152){
			getBase64Image(dataURL,fun);
		}else{
			mui.hideLoading();
			var list = {
				dataURL: dataURL,
				type: "image/" + ext
			}
			fun(list);
		}
		/*canvas.toBlob(function(blob) {
			if(blob.size > 2048 * 1024) {
				getBase64Image(dataURL,fun);
			} else {
				mui.hideLoading();
				let lsit = {
					dataURL: dataURL,
					type: "image/" + ext
				}
				fun(lsit);
			}
		})*/
	}
}


/*
 * 压缩图片
 */
function getBase64Image2m(imgurl, fun) {
	//mui.toast("开始压缩图片");
	
	console.log(getblobSize(),"111");
	
	return;
	mui.showLoading("正在压缩");
	let img = new Image();
	img.src = imgurl;
	let div = document.createElement('div');
	div.appendChild(img);
	img.onload = function() {
		var canvas = document.createElement("canvas");
		let imgw = img.width / 1.5;
		let imgh = img.height / 1.5;
		canvas.width = imgw;
		canvas.height = imgh;
		var ctx = canvas.getContext("2d");
		ctx.drawImage(img, 0, 0, imgw, imgh);
		var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
		var dataURL = canvas.toDataURL("image/" + ext);
		canvas.toBlob(function(blob) {
			if(blob.size > 2048 * 1024) {
				getBase64Image(dataURL,fun);
			} else {
				mui.hideLoading();
				let lsit = {
					dataURL: dataURL,
					type: "image/" + ext
				}
				fun(lsit);
			}
		})
	}
}

function getblobSize(imgurl) {
	//mui.toast("开始压缩图片");
	
	
	
	
	
	let img = new Image();
	img.src = imgurl;
	let div = document.createElement('div');
	div.appendChild(img);
	img.onload = function() {
		var canvas = document.createElement("canvas");
		let imgw = img.width;
		let imgh = img.height;
		canvas.width = imgw;
		canvas.height = imgh;
		var ctx = canvas.getContext("2d");
		ctx.drawImage(img, 0, 0, imgw, imgh);
		var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
		var dataURL = canvas.toDataURL("image/" + ext);
		canvas.toBlob(function(blob) {
			
				
			
				
				let lsit = {
					dataURL: dataURL,
					type: "image/" + ext,
					size : blob,
				}
				console.log("size",blob);
				return lsit;
		})
	}
}

 function getBase64(img){
 	
        function getBase64Image6(img,width,height) {//width、height调用时传入具体像素值，控制大小 ,不传则默认图像大小
          var canvas = document.createElement("canvas");
          canvas.width = width ? width : img.width;
          canvas.height = height ? height : img.height;
          var ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
          var dataURL = canvas.toDataURL();
          return dataURL;
        }
        var image = new Image();
        image.crossOrigin = 'anonymous';
        /*img.setAttribute('crossOrigin', 'anonymous');*/
        image.src = img;
        var deferred=$.Deferred();
        if(img){
          image.onload =function (){
            deferred.resolve(getBase64Image6(image));//将base64传给done上传处理
          }
          return deferred.promise();//问题要让onload完成后再return sessionStorage['imgTest']
        }
    }

//将base64转换为文件
function dataURLtoFile(dataurl, filename) {
	var arr = dataurl.split(',');
	console.log(arr);
	var mime = arr[0].match(/:(.*?);/)[1];
	console.log(mime);
	var bstr = atob(arr[1]);
	console.log(bstr);
	var n = bstr.length;
	var u8arr = new Uint8Array(n);
	while(n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	console.log(u8arr);
	return new File([u8arr], filename, {
		type: mime
	});
}

/*
 * base64转blob
 */
function b64toBlob(b64Data, contentType, sliceSize) {
	contentType = contentType || '';
	sliceSize = sliceSize || 512;
	var byteCharacters = atob(b64Data.substring(b64Data.indexOf(',') + 1));
	var byteArrays = [];
	for(var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
		var slice = byteCharacters.slice(offset, offset + sliceSize);
		var byteNumbers = new Array(slice.length);
		for(var i = 0; i < slice.length; i++) {
			byteNumbers[i] = slice.charCodeAt(i);
		}
		var byteArray = new Uint8Array(byteNumbers);
		byteArrays.push(byteArray);
	}
	var blob = new Blob(byteArrays, {
		type: contentType
	});
	return blob;
}



//验证非法字符
 function checkStr(strTest) {
     var pat = new RegExp("[^a-zA-Z0-9\_\u4e00-\u9fa5]", "i");
     var strArr = strTest.split("");
     for (var i = 0; i < strArr.length; i++) {
         var str = strTest.charAt(i);
         if (pat.test(strArr[i]) == true) {
             strArr[i] = "()";
             console.log("含有非法字符");
             return false
         }
     }
     return true
 }  
 
//时间戳转时间
function add0(m){return m<10?'0'+m:m }
function getLocalTime(shijianchuo){
	//shijianchuo是整数，否则要parseInt转换
	var time = new Date(shijianchuo);
	var y = time.getFullYear();
	var m = time.getMonth()+1;
	var d = time.getDate();
	var h = time.getHours();
	var mm = time.getMinutes();
	var s = time.getSeconds();
	return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
}
/*
function getLocalTime(now) { 
     var year=now.getFullYear(); 
     var month=now.getMonth()+1; 
     var date=now.getDate(); 
     var hour=now.getHours(); 
     var minute=now.getMinutes(); 
     var second=now.getSeconds(); 
     return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second; 
} */


//随机数
function getmath(){
	return parseInt(Math.random()*9+1);   
}
